<?php

namespace app\batch;

use think\Db;

use think\console\Command;
use app\facade\Redis;

use think\console\Input;
use think\console\Output;
use app\models\{Autoorder, Order, OrderProduct, Agent, Product};

class AutoOrders extends Command
{
    protected $open = false;
    protected function configure()
    {
        $this->setName('AutoOrders')->setDescription('刷单');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->doCron();
        die();
    }

    protected function doCron()
    {
        $time = date('H');
        if ($time < 8 || $time > 21) {
            echo '没有到刷单时间';
            die;
        }
        //太久的订单自动结算
        (new Order())->where(['issystem' => 2, 'status' => [2, 3]])
            ->whereTime('ordertime', '<=', date('Y-m-d H:i:s', time() - 172800))->chunk(10, function ($item) {
                foreach ($item as $items) {
                    (new Order())->where('id', $items['id'])->update(['status' => 4]);
                    echo $items['id'] . '自动结算';
                }
            });
        (new Autoorder())->where(['status' => 1])->chunk(20, function ($list) {
            //查询下级订单的总重
            foreach ($list as $lists) {
                $rdsname = 'AutoOrders' . $lists['id'];
                $frtimes = Redis::get($rdsname);
                if ($frtimes) {
                    echo '跳过' . date('Y-m-d H:i:s');
                    continue;
                } else {
                    Redis::setex($rdsname, 720, 720);
                }
                //先查找上次记录
                $address = json_decode($lists['parpam'], true);
                $number = rand(0, count($address) - 1);
                $status = rand(2, 3);
                $order = [
                    'user_id' => 1,
                    'ordersn' => reordersn(new Order()),
                    'agentid' => $lists['agentid'],
                    'name' => $address[$number]['name'],
                    'mobile' => $address[$number]['mobile'],
                    'province' =>  $lists['province'],
                    'city' =>  $lists['city'],
                    'area' =>  $lists['area'],
                    'street' =>  $lists['street'],
                    'posaddress' => '',
                    'address' => $address[$number]['address'],
                    'lat' => 113.108410,
                    'lon' => 28.212606,
                    'appointment' => date('Y-m-d H:i:s', time() + 1800 + rand(60, 1800)),
                    'info' => $data['info'] ?? '',
                    'status' => 1,
                    'coupon' => 0,
                    'cmoney' => 0,
                    'dict' => 100,
                    'payment' => 1,
                    'ptotal' => 0,
                    'status' => $status,
                    'ccount' => 0,
                    'dicttotal' => 0,
                    'total' => 0,
                    'issystem' => 2
                ];
                $order['orderid'] = $lists['rider'];
                $order['ordertime'] = date('Y-m-d H:i:s', time() + rand(60, 1800));
                if ($status == 3 || $status == 4) {
                    $order['message'] = 2;
                    if ($status == 4) {
                        $order['endtime'] = date('Y-m-d H:i:s', time() + 7200 + rand(60, 1800));
                    }
                }
                $limit = rand(1, 2);
                $orderproduct = [];
                $product = (new Product())->orderRaw("rand()")->where('price', '<=', 60)->limit($limit)
                    ->where(['isdel' => 1, 'isshow' => 1, 'agentid' => $lists['agentid']])->select();
                foreach ($product as $products) {
                    //查找下面有没有相关服务人员
                    $products['number'] = rand(1, 2);
                    if (count($product) > 1) {
                        $products['number'] = 1;
                    }
                    $orderproduct[] = [
                        'ordersn' => $order['ordersn'],
                        'agentid' => $products['agentid'],
                        'cate' => $products['cate'],
                        'subcate' => $products['subcate'],
                        'productid' => $products['id'],
                        'title' =>  $products['title'],
                        'descs' =>  $products['descs'],
                        'images' =>  $products['images'],
                        'price' =>  $products['price'],
                        'number' =>  $products['number'],
                        'cnumber' => 0,
                        'cid' => 0,
                    ];
                    $order['ptotal'] += floor($products['number'] * $products['price'] * 1000) / 1000;
                }
                $order['dicttotal'] = $order['ptotal'];
                $order['total'] = round(($order['ptotal']), 2);
                if ($order['total'] <= 0) {
                    $order['total'] = 0;
                }
                if (count($orderproduct) > 0) {
                    Db::startTrans();
                    try {
                        (new Order())->save($order);
                        (new OrderProduct())->allowfield(true)->saveAll($orderproduct);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        echo $e->getMessage();
                    }
                    echo '下单成功';
                }
            }
        });
    }
}
